package com.live.crawler.selenium;

import com.live.crawler.entity.DyBarrageMessage;
import com.live.crawler.listener.DyBarrageListener;
import com.live.crawler.util.UniqueQueue;
import lombok.Data;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 谷歌模拟
 * @author chengjian 
 * @date 2022/6/18
 */
@Data
public class DySelenium {
    /** 抖音直播间地址 **/
    private final String liveUrl;

    /** 是否过滤用户进入直播间进场弹幕消息 **/
    private final boolean filterJoinUserMsg;

    /** 抖音弹幕监听器 **/
    private final DyBarrageListener dyBarrageListener;

    /** 弹幕队列 最大容量2000 **/
    private UniqueQueue<DyBarrageMessage> uniqueQueue = new UniqueQueue<>(2000);

    public DySelenium(String liveUrl, boolean filterJoinUserMsg, DyBarrageListener dyBarrageListener) {
        this.liveUrl = liveUrl;
        this.dyBarrageListener = dyBarrageListener;
        this.filterJoinUserMsg = filterJoinUserMsg;
    }


    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    DyBarrageMessage barrageMessage = uniqueQueue.poll();
                    if (barrageMessage != null) {
                        dyBarrageListener.consume(barrageMessage);
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String path = System.getProperty("user.dir");
                    String fileName = System.getProperty("os.name").toLowerCase().startsWith("windows")
                            ? "/driver/chromedriver.exe"
                            : "/driver/chromedriver";
                    System.setProperty("webdriver.chrome.driver", path + fileName);
                    ChromeOptions options = new ChromeOptions();
                    options.addArguments("headless");
                    ChromeDriver driver = new ChromeDriver(options);
                    driver.get(liveUrl);
                    while (true) {
                        try {
                            WebElement element = driver.findElements(By.cssSelector(".webcast-chatroom___items"))
                                    .get(0);
                            String value = element.getAttribute("innerHTML");
                            addToQueue(value);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void addToQueue(String html) {
        Elements items = Jsoup.parse(html).select(".webcast-chatroom___item");
        for (Element item : items) {
            if (item.selectFirst(".webcast-chatroom__room-message") != null) {
                continue;
            }
            Element textElement = item.selectFirst("span[class='webcast-chatroom___content-with-emoji-text']");
            if (filterJoinUserMsg && textElement == null) {
                continue;
            }
            DyBarrageMessage barrageMessage = new DyBarrageMessage();
            if (textElement != null) {
                barrageMessage.setMessage(textElement.text());
            }
            barrageMessage.setId(item.attr("data-id"));
            Element nickElement = item.selectFirst("span[class='tfObciRM']");
            if (nickElement != null) {
                barrageMessage.setNickname(nickElement.text());
            }

            uniqueQueue.add(barrageMessage);
        }
    }


    public static void main(String[] args) {
        // 后缀为直播间id
        String url = "https://live.douyin.com/76161563035";
        DyBarrageListener listener = message -> System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()) + "-【" + message.getNickname()
                + "】" + message.getMessage() + "-【ID：" + message.getId() +"】");
        new DySelenium(url, true, listener).start();
    }

}
